package com.yanqu.road.dao.impl.activity.suitang.config;

import com.yanqu.road.dao.impl.activity.suitang.CompositeKey;
import com.yanqu.road.dao.impl.activity.suitang.GenericDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import static com.yanqu.road.entity.buildDaoUtil.BuildConfigSql.getKey;
import static com.yanqu.road.entity.buildDaoUtil.BuildConfigSql.getSelectSql;

public class GenericConfigDaoImpl extends GenericDao {

    public <T> Map<Integer, T> getGenericConfigMap(int activityId, Class<T> type) {
        String genericConfigSql = getSelectSql(type);
        List<String> keys = getKey(type);
        if (keys.isEmpty()) return null;
        return executeQuery(genericConfigSql, new Object[]{activityId}, type, rs -> {
            try {
                if(keys.size() == 1) {
                    return rs.getInt(keys.get(0));
                } else if (keys.size() == 2) {
                    return rs.getInt(keys.get(0)) * 10 + rs.getInt(keys.get(1));
                }
                return rs.getInt(keys.get(0));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public <T> Map<CompositeKey, T> getGenericConfigMapCompositeKey(int activityId, Class<T> type) {
        String genericConfigSql = getSelectSql(type);
        List<String> keys = getKey(type);
        if (keys.isEmpty()) return null;
        List<Object> keyValues = new ArrayList<>();
        Function<ResultSet, CompositeKey> keyMapper = rs -> {
            try {
                for (String key : keys) {
                    keyValues.add(rs.getInt(key));
                }
                return new CompositeKey(keyValues);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        };
        return executeQuery(genericConfigSql, new Object[]{activityId}, type, keyMapper);
    }
}
